package com.wxzz.elearing.course.service.impl;

import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.chatroom.CreateChatRoomResult;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.course.amqp.producer.CourseProducer;
import com.wxzz.elearing.course.dto.StudyPlanDto;
import com.wxzz.elearing.course.dto.StudyPlanInsDto;
import com.wxzz.elearing.course.dto.WxUserStudyPlanDto;
import com.wxzz.elearing.course.dto.WxUserStudyPlanInsDto;
import com.wxzz.elearing.course.entity.*;
import com.wxzz.elearing.course.mapper.*;
import com.wxzz.elearing.course.service.IStudyPlanService;
import com.wxzz.elearing.course.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.constants.RoomConstants;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.MD5Util;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

@Service

public class StudyPlanServiceImpl extends ServiceImpl<StudyPlanMapper, StudyPlan> implements IStudyPlanService {

    @Autowired
    private StudyPlanMapper studyPlanMapper;

    @Autowired
    private StudyPlanUnitMapper studyPlanUnitMapper;

    @Autowired
    private StudyPlanCurriculumMapper studyPlanCurriculumMapper;

    @Override
    @Transactional
    public ReturnVO saveStudyPlan(Long enterpriseId, StudyPlanInsDto studyPlanInsDto) {
        StudyPlan studyPlan = new StudyPlan();
        BeanUtils.copyProperties(studyPlanInsDto, studyPlan);
        studyPlan.setEnterpriseId(enterpriseId);
        if (studyPlanInsDto.getId() == null) {
            //新增学习计划详情
            studyPlanMapper.insert(studyPlan);
        } else {
            //更新 将原有的试题删除重新添加
            studyPlanMapper.updateById(studyPlan);
            List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.selectList(new LambdaQueryWrapper<StudyPlanUnit>()
                    .eq(StudyPlanUnit::getStudyPlanId, studyPlan.getId()));
            studyPlanUnits.forEach(studyPlanUnit -> {
                //删除学习计划单元
                studyPlanUnitMapper.deleteById(studyPlanUnit.getId());
                //删除学习计划单元关联课程
                studyPlanCurriculumMapper.deleteStudyPlanCurriculumByStudyPlanUnitId(studyPlanUnit.getId());
            });
        }
        if (studyPlanInsDto.getStudyPlanUnits() != null) {
            for (StudyPlanUnit studyPlanUnit : studyPlanInsDto.getStudyPlanUnits()) {
                //新增学习计划单元
                studyPlanUnit.setId(null);
                studyPlanUnit.setStudyPlanId(studyPlan.getId());
                studyPlanUnitMapper.insert(studyPlanUnit);
//                if (studyPlanUnit.getCurriculumList() != null) {
//                    for (Curriculum curriculum : studyPlanUnit.getCurriculumList()) {
//                        StudyPlanCurriculum studyPlanCurriculum = new StudyPlanCurriculum();
//                        studyPlanCurriculum.setCurriculumId(curriculum.getId());
//                        studyPlanCurriculum.setStudyPlanUnitId(studyPlanUnit.getId());
//                        studyPlanCurriculumMapper.insert(studyPlanCurriculum);
//                    }
//                }
                if (studyPlanUnit.getCurriculumIds() != null) {
                    for (Long curriculumId : studyPlanUnit.getCurriculumIds()) {
                        StudyPlanCurriculum studyPlanCurriculum = new StudyPlanCurriculum();
                        studyPlanCurriculum.setCurriculumId(curriculumId);
                        studyPlanCurriculum.setStudyPlanUnitId(studyPlanUnit.getId());
                        studyPlanCurriculumMapper.insert(studyPlanCurriculum);
                    }
                }
            }
        }
        //学习计划到期提醒
        if (studyPlan.getFinishTime() != null) {
            courseProducer.remindStudyPlan(studyPlan.getId(), studyPlan.getFinishTime());
        }
        return new ReturnVO<>("学习计划新增或修改成功", studyPlan.getId());
    }

    @Override
    public ReturnVO deleteStudyPlanById(Long studyPlanById) {
        studyPlanMapper.deleteById(studyPlanById);
        return new ReturnVO<>("学习计划删除成功", studyPlanById);
    }

    @Override
    public ReturnVO updateStudyPlanFinish() {
        //查询所有已上架的学习计划
        List<StudyPlan> studyPlans = studyPlanMapper.selectList(new LambdaQueryWrapper<StudyPlan>()
                .eq(StudyPlan::getStatus, 1));
        for (StudyPlan studyPlan : studyPlans) {
            //查询学习计划绑定的用户
            List<WxUserStudyPlan> wxUserStudyPlans = wxUserStudyPlanMapper.selectList(new LambdaQueryWrapper<WxUserStudyPlan>()
                    .eq(WxUserStudyPlan::getStudyPlanId, studyPlan.getId())
                    .eq(WxUserStudyPlan::getExamStatus, 1));
            Integer finishedNum = 0;
            for (WxUserStudyPlan wxUserStudyPlan : wxUserStudyPlans) {
                setStudySchedule(wxUserStudyPlan.getWxUserId(), studyPlan);
                //查看进度是否为100 为100则完成
                if (new BigDecimal("100.00").equals(studyPlan.getStudySchedule())) {
                    finishedNum = finishedNum + 1;
                }
            }
            //学习人数
            studyPlan.setStudyNum(wxUserStudyPlans.size());
            //完成人数
            studyPlan.setFinishedNum(finishedNum);
            studyPlan.setUnfinishedNum(wxUserStudyPlans.size() - finishedNum);
            studyPlanMapper.updateById(studyPlan);
        }
        return new ReturnVO<>("学习计划状态更新成功", null);
    }

    @Autowired
    private CourseProducer courseProducer;

    @Override
    public ReturnVO<JgPageVo<List<StudyPlan>>> listStudyPlan(Long enterpriseId, StudyPlanDto studyPlanDto) {
        PageHelper.startPage(studyPlanDto.getCurPage(), studyPlanDto.getMaxPage());
        QueryWrapper<StudyPlan> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("enterprise_id", enterpriseId);
        if (StringUtils.isNotBlank(studyPlanDto.getPlanName())) {
            queryWrapper.like("plan_name", studyPlanDto.getPlanName());
        }
        if (studyPlanDto.getStatus() != null) {
            queryWrapper.like("status", studyPlanDto.getStatus());
        }
        List<StudyPlan> list = studyPlanMapper.selectList(queryWrapper);
        for (StudyPlan studyPlan : list) {
            //学习期数
            List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.selectList(new LambdaQueryWrapper<StudyPlanUnit>()
                    .eq(StudyPlanUnit::getStudyPlanId, studyPlan.getId()));
            studyPlan.setStudyPlanUnitNum(studyPlanUnits.size());
            //课程门数
            Integer curriculumNum = 0;
            for (StudyPlanUnit studyPlanUnit : studyPlanUnits) {
                Integer count = studyPlanCurriculumMapper.selectCount(new LambdaQueryWrapper<StudyPlanCurriculum>()
                        .eq(StudyPlanCurriculum::getStudyPlanUnitId, studyPlanUnit.getId()));
                curriculumNum = curriculumNum + count;
            }
            studyPlan.setCurriculumNum(curriculumNum);
        }
        return new ReturnVO("学习计划列表查询成功", new JgPageVo(new PageInfo<>(list)));
    }

    @Override
    public ReturnVO<JgPageVo<List<StudyPlan>>> wxListStudyPlan(Long wxUserId, Long enterpriseId, StudyPlanDto studyPlanDto) {
        PageHelper.startPage(studyPlanDto.getCurPage(), studyPlanDto.getMaxPage());
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("enterprise_id", enterpriseId);
//        if (StringUtils.isNotBlank(studyPlanDto.getPlanName())) {
//            queryWrapper.like("plan_name", studyPlanDto.getPlanName());
//        }
//        List<StudyPlan> studyPlans = studyPlanMapper.selectList(queryWrapper);
        List<StudyPlan> studyPlans = wxUserStudyPlanMapper.listWxUserStudyPlanByWxUserId(wxUserId, enterpriseId, studyPlanDto);
        for (StudyPlan studyPlan : studyPlans) {
            setStudySchedule(wxUserId, studyPlan);
            //学习期数
            List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.selectList(new LambdaQueryWrapper<StudyPlanUnit>()
                    .eq(StudyPlanUnit::getStudyPlanId, studyPlan.getId()));
            studyPlan.setStudyPlanUnitNum(studyPlanUnits.size());
            //课程门数
            Integer curriculumNum = 0;
            for (StudyPlanUnit studyPlanUnit : studyPlanUnits) {
                Integer count = studyPlanCurriculumMapper.selectCount(new LambdaQueryWrapper<StudyPlanCurriculum>()
                        .eq(StudyPlanCurriculum::getStudyPlanUnitId, studyPlanUnit.getId()));
                curriculumNum = curriculumNum + count;
            }
            studyPlan.setCurriculumNum(curriculumNum);
        }
        return new ReturnVO("学习计划列表查询成功", new JgPageVo(new PageInfo<>(studyPlans)));
    }

    @Autowired
    private WxUserCurriculumMapper wxUserCurriculumMapper;

    @Override
    public ReturnVO<List<StudyPlanUnit>> listCurriculumByStudyPlanId(Long wxUserId, Long studyPlanId) {
        List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.listStudyPlanUnitByStudyPlanId(studyPlanId);
        for (StudyPlanUnit studyPlanUnit : studyPlanUnits) {
            List<Curriculum> curriculumList = curriculumMapper.listCurriculumByStudyPlanUnitId(studyPlanUnit.getId());
            //单元状态 0-未完成 1-已完成
            Integer status = 1;
            for (Curriculum curriculum : curriculumList) {
                setStudySchedule(wxUserId, curriculum);
                //如果有一节课不为100%则为未完成
                if (new BigDecimal("100.00").compareTo(curriculum.getStudySchedule()) != 0) {
                    status = 0;
                }
                //学习人数
                Integer curriculumStudyNum = wxUserCurriculumMapper.selectCount(new LambdaQueryWrapper<WxUserCurriculum>()
                        .eq(WxUserCurriculum::getCurriculumId, curriculum.getId())
                        .eq(WxUserCurriculum::getStatus, 1));
                curriculum.setCurriculumStudyNum(curriculumStudyNum);
                //如果是企业购买的课程,则进行特殊处理
                if (curriculum.getIsEnterpriseBuy() != null && curriculum.getIsEnterpriseBuy() == 1) {
                    Curriculum oldCurriculum = curriculumMapper.selectById(curriculum.getOldCurriculumId());
                    if (oldCurriculum != null) {
                        //设置原课程的基础信息
                        curriculum.setId(oldCurriculum.getId());
                        curriculum.setCurriculumTitle(oldCurriculum.getCurriculumTitle());
                        curriculum.setCurriculumDescribe(oldCurriculum.getCurriculumDescribe());
                        curriculum.setCurriculumBanner(oldCurriculum.getCurriculumBanner());
                        curriculum.setCurriculumFile(oldCurriculum.getCurriculumFile());
                        curriculum.setCurriculumFileName(oldCurriculum.getCurriculumFileName());
                        curriculum.setCurriculumFileSize(oldCurriculum.getCurriculumFileSize());
                    }
                }
            }
            studyPlanUnit.setStatus(status);
            studyPlanUnit.setCurriculumList(curriculumList);
        }
        return new ReturnVO("学习计划中的课程查询成功", studyPlanUnits);
    }

    @Override
    public ReturnVO listStudyPlanUnitByStudyPlanId(Long studyPlanId) {
        List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.listStudyPlanUnitByStudyPlanId(studyPlanId);
        return new ReturnVO("学习单元查询成功", studyPlanUnits);
    }

    @Override
    public ReturnVO<StudyPlanInsDto> selectStudyPlanDetail(Long wxUserId, Long studyPlanId) {
        StudyPlan studyPlan = studyPlanMapper.selectById(studyPlanId);
        Optional.ofNullable(studyPlan).orElseThrow(() -> new ServiceException("该学习计划已不存在"));
        StudyPlanInsDto studyPlanInsDto = new StudyPlanInsDto();
        BeanUtils.copyProperties(studyPlan, studyPlanInsDto);
        List<StudyPlanUnit> studyPlanUnits = studyPlanUnitMapper.listStudyPlanUnitByStudyPlanId(studyPlanId);
        //查询单元对应的课程
        Integer curriculumNum = 0;
        //单元状态 0-未完成 1-已完成
        Integer status = 1;
        for (StudyPlanUnit studyPlanUnit : studyPlanUnits) {
            List<Curriculum> curriculumList = studyPlanUnitMapper.selectCurriculumByStudyPlanUnitId(studyPlanUnit.getId());
            for (Curriculum curriculum : curriculumList) {
                setStudySchedule(wxUserId, curriculum);
                //如果有一节课不为100%则为未完成
                if (new BigDecimal("100.00").compareTo(curriculum.getStudySchedule()) != 0) {
                    status = 0;
                }
                //学习人数
                Integer curriculumStudyNum = wxUserCurriculumMapper.selectCount(new LambdaQueryWrapper<WxUserCurriculum>()
                        .eq(WxUserCurriculum::getCurriculumId, curriculum.getId())
                        .eq(WxUserCurriculum::getStatus, 1));
                curriculum.setCurriculumStudyNum(curriculumStudyNum);
                //如果是企业购买的课程,则进行特殊处理
                if (curriculum.getIsEnterpriseBuy() != null && curriculum.getIsEnterpriseBuy() == 1) {
                    Curriculum oldCurriculum = curriculumMapper.selectById(curriculum.getOldCurriculumId());
                    if (oldCurriculum != null) {
                        //设置原课程的基础信息
                        curriculum.setCurriculumTitle(oldCurriculum.getCurriculumTitle());
                        curriculum.setCurriculumDescribe(oldCurriculum.getCurriculumDescribe());
                        curriculum.setCurriculumBanner(oldCurriculum.getCurriculumBanner());
                        curriculum.setCurriculumFile(oldCurriculum.getCurriculumFile());
                        curriculum.setCurriculumFileName(oldCurriculum.getCurriculumFileName());
                        curriculum.setCurriculumFileSize(oldCurriculum.getCurriculumFileSize());
                    }
                }
            }
            curriculumNum = curriculumNum + curriculumList.size();
            studyPlanUnit.setStatus(status);
            studyPlanUnit.setCurriculumList(curriculumList);
        }
        //学习人数
        List<WxUserStudyPlan> wxUserStudyPlans = wxUserStudyPlanMapper.selectList(new LambdaQueryWrapper<WxUserStudyPlan>()
                .eq(WxUserStudyPlan::getStudyPlanId, studyPlanId)
                .eq(WxUserStudyPlan::getExamStatus, 0));
        //课程单元数量
        studyPlanInsDto.setCurriculumNum(curriculumNum);
        studyPlanInsDto.setStudyPlanUnits(studyPlanUnits);
        studyPlanInsDto.setStudyPlanUnitNum(studyPlanUnits.size());
        if (wxUserId != null) {
            setStudySchedule(wxUserId, studyPlanInsDto);
        }
        return new ReturnVO("学习计划查询成功", studyPlanInsDto);
    }

    @Autowired
    private WxUserStudyPlanMapper wxUserStudyPlanMapper;

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Override
    public ReturnVO<JgPageVo<List<WxUserStudyPlan>>> selectWxUserStudyPlanByStudyPlanId(WxUserStudyPlanDto wxUserStudyPlanDto) {
        PageHelper.startPage(wxUserStudyPlanDto.getCurPage(), wxUserStudyPlanDto.getMaxPage());
        List<WxUserStudyPlan> wxUserStudyPlans = wxUserStudyPlanMapper.selectList(new LambdaQueryWrapper<WxUserStudyPlan>()
                .eq(WxUserStudyPlan::getStudyPlanId, wxUserStudyPlanDto.getStudyPlanId())
                .eq(WxUserStudyPlan::getExamStatus, 0));
        for (WxUserStudyPlan wxUserStudyPlan : wxUserStudyPlans) {
            //查询用户信息
            ReturnVO<String> stringReturnVO = wxUserApiFeign.selectWxUserByWxUserId(wxUserStudyPlan.getWxUserId());
            JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
            wxUserStudyPlan.setNickname(jsonObject.getString("nickname"));
            wxUserStudyPlan.setIcon(jsonObject.getString("icon"));
            wxUserStudyPlan.setPhone(jsonObject.getString("phone"));
            wxUserStudyPlan.setOrganizationName(jsonObject.getString("organizationName"));
            wxUserStudyPlan.setIdentityName(jsonObject.getString("identityName"));
            StudyPlan studyPlan = studyPlanMapper.selectById(wxUserStudyPlan.getStudyPlanId());
            if (studyPlan != null) {
                setStudySchedule(wxUserStudyPlan.getWxUserId(), studyPlan);
                wxUserStudyPlan.setStudySchedule(studyPlan.getStudySchedule());
            }
        }
        return new ReturnVO("学习人员查询成功", new JgPageVo<>(new PageInfo(wxUserStudyPlans)));
    }


    @Override
    public ReturnVO saveWxUserStudyPlan(WxUserStudyPlanInsDto wxUserStudyPlanInsDto) {
        StudyPlan studyPlan = studyPlanMapper.selectById(wxUserStudyPlanInsDto.getStudyPlanId());
        Optional.ofNullable(studyPlan).orElseThrow(() -> new ServiceException("该学习计划已不存在"));
        if (wxUserStudyPlanInsDto.getWxUserIds() != null) {
            //先全部禁考
            List<WxUserStudyPlan> wxUserStudyPlans = wxUserStudyPlanMapper.selectList(new LambdaQueryWrapper<WxUserStudyPlan>()
                    .eq(WxUserStudyPlan::getExamStatus, 0)
                    .eq(WxUserStudyPlan::getStudyPlanId, wxUserStudyPlanInsDto.getStudyPlanId()));
            for (WxUserStudyPlan wxUserStudyPlan : wxUserStudyPlans) {
                //禁考
                wxUserStudyPlan.setExamStatus(1);
                wxUserStudyPlanMapper.updateById(wxUserStudyPlan);
            }
            //重新分配
            for (Long wxUserId : wxUserStudyPlanInsDto.getWxUserIds()) {
                WxUserStudyPlan wxUserStudyPlan = wxUserStudyPlanMapper.selectOne(new LambdaQueryWrapper<WxUserStudyPlan>()
                        .eq(WxUserStudyPlan::getStudyPlanId, wxUserStudyPlanInsDto.getStudyPlanId())
                        .eq(WxUserStudyPlan::getWxUserId, wxUserId));
                //如果不存在则添加上去
                if (wxUserStudyPlan == null) {
                    WxUserStudyPlan save = new WxUserStudyPlan();
                    save.setStudyPlanId(studyPlan.getId());
                    save.setWxUserId(wxUserId);
                    wxUserStudyPlanMapper.insert(save);
                } else {
                    //如果存在则直接改为可考
                    wxUserStudyPlan.setExamStatus(0);
                    wxUserStudyPlanMapper.updateById(wxUserStudyPlan);
                }
            }
            //todo 小程序订阅
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            systemMessageMqDto.setMessageDetail("您已被纳入" + studyPlan.getPlanName() + "学习计划中,该计划将于" + studyPlan.getFinishTime() + "到期,请尽快学习");
            systemMessageMqDto.setMessageTitle("安排学习计划");
            systemMessageMqDto.setWxUserIds(wxUserStudyPlanInsDto.getWxUserIds());
            courseProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        }
        return new ReturnVO("考试人员分配成功", studyPlan.getId());
    }

    @Override
    public ReturnVO<List<JSONObject>> selectWxUserStudyPlan(Long wxUserStudyPlanId, List<Long> wxUserIds) {
        List<JSONObject> wxUserStudyPlans = Lists.newArrayList();
        for (Long wxUserId : wxUserIds) {
            //查询用户绑定可考的考试
            WxUserStudyPlan wxUserStudyPlan = wxUserStudyPlanMapper.selectOne(new LambdaQueryWrapper<WxUserStudyPlan>()
                    .eq(WxUserStudyPlan::getStudyPlanId, wxUserStudyPlanId)
                    .eq(WxUserStudyPlan::getWxUserId, wxUserId)
                    .eq(WxUserStudyPlan::getExamStatus, 0));
            if (wxUserStudyPlan != null) {
                wxUserStudyPlans.add(JSONObject.parseObject(JSONObject.toJSONString(wxUserStudyPlan)));
            }
        }
        return new ReturnVO("学习计划绑定人员查询成功", wxUserStudyPlans);
    }

    //极光初始化
    JMessageClient client = new JMessageClient(RoomConstants.APP_KEY, RoomConstants.MASTER_SECRET);

    @Override
    public ReturnVO<Map> initIM(Long studyPlanId) {
        StudyPlan studyPlan = studyPlanMapper.selectById(studyPlanId);
        if (studyPlan == null) {
            throw new ServiceException("该学习计划不存在");
        }
        if (studyPlan.getRoomId() == null) {
            try {
                //聊天室懒加载
                CreateChatRoomResult chatRoom = client.createChatRoom(ChatRoomPayload.newBuilder()
                        .setOwnerUsername("admin")
                        .setName(studyPlan.getPlanName())
                        .build());
                studyPlan.setRoomId(chatRoom.getChatroom_id());
                studyPlanMapper.updateById(studyPlan);
            } catch (Exception e) {
                throw new ServiceException("聊天室初始化异常:" + e.getMessage());
            }
        }
        Map<String, String> map = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        String time = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        map.put("appkey", RoomConstants.APP_KEY);
        map.put("random_str", uuid);
        map.put("signature", MD5Util.md5Encrypt32Upper("appkey=90404644792112144baf94ae&timestamp=" + time + "&random_str=" + uuid + "&key=" + RoomConstants.MASTER_SECRET));
        map.put("timestamp", time);
        map.put("roomId", String.valueOf(studyPlan.getRoomId()));
        return new ReturnVO("聊天室初始化成功", map);
    }

//    @Override
//    public ReturnVO saveStudyPlanUnit(StudyPlanUnit studyPlanUnit) {
//        if (studyPlanUnit.getId() == null) {
//            studyPlanUnitMapper.insert(studyPlanUnit);
//        } else {
//            studyPlanUnitMapper.updateById(studyPlanUnit);
//        }
//        return new ReturnVO("新增或修改学习单元成功", studyPlanUnit.getId());
//    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询学习计划进度
     *
     * @param studyPlan
     */
    protected void setStudySchedule(Long wxUserId, StudyPlan studyPlan) {
        List<Curriculum> curriculumList = studyPlanUnitMapper.listStudyPlanUnit(studyPlan.getId());
        //课程进度总和
        BigDecimal studyScheduleTotal = new BigDecimal("0.00");
        for (Curriculum curriculum : curriculumList) {
            setStudySchedule(wxUserId, curriculum);
            studyScheduleTotal = studyScheduleTotal.add(curriculum.getStudySchedule());
        }
        //课程进度总和/课程数量 = 培训计划的进度
        if (curriculumList.size() != 0) {
            studyPlan.setStudySchedule(studyScheduleTotal.divide(new BigDecimal(String.valueOf(curriculumList.size())), 2, BigDecimal.ROUND_HALF_UP));
            studyPlan.setSectionName(redisTemplate.opsForValue().get(RedisConstants.PLAN_SECTION_LAST_SEE + wxUserId + ":" + studyPlan.getId()));
        } else {
            //课程数量为0则进度直接为100%
            studyPlan.setStudySchedule(new BigDecimal("0.00"));
        }
    }

    @Autowired
    private CurriculumMapper curriculumMapper;

    /**
     * 查询课程进度
     */
    protected void setStudySchedule(Long wxUserId, Curriculum curriculum) {
        //总章节数量
        Integer allSectionNum = curriculumMapper.selectCountByCurriculumId(curriculum.getId());
        if (allSectionNum != 0) {
            //用户完成的章节数量
            Integer finishSectionNum = curriculumMapper.selectIsPassByWxUserId(curriculum.getId(), wxUserId);
            curriculum.setStudySchedule(new BigDecimal(String.valueOf(finishSectionNum))
                    .divide(new BigDecimal(String.valueOf(allSectionNum)), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100.00")));
        } else {
            //总章节数量为0则进度直接为100%
            curriculum.setStudySchedule(new BigDecimal("0.00"));
        }
    }
}
